package com.atguigu.distributed.lock.leecode.tree;

import com.atguigu.distributed.lock.leecode.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class TreetoLinkNodes {
    public void flatten(TreeNode root){
        List<TreeNode> list = new ArrayList<>();
        preorderTraversal(root,list);
        for (int i = 1; i < list.size(); i++) {
            TreeNode pre = list.get(i-1),curr = list.get(i);
            pre.left = null;
            pre.right = curr;
        }
    }
    public void preorderTraversal(TreeNode root,List<TreeNode> list){
        if(root!=null){
            list.add(root);
            preorderTraversal(root.left,list);
            preorderTraversal(root.right,list);
        }
    }
}
class Solution {
    public void flatten(TreeNode root) {
        List<TreeNode> list = new ArrayList<TreeNode>();
        preorderTraversal(root, list);
        int size = list.size();
        for (int i = 1; i < size; i++) {
            TreeNode prev = list.get(i - 1), curr = list.get(i);
            prev.left = null;
            prev.right = curr;
        }
    }

    public void preorderTraversal(TreeNode root, List<TreeNode> list) {
        if (root != null) {
            list.add(root);
            preorderTraversal(root.left, list);
            preorderTraversal(root.right, list);
        }
    }
}

